import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  OnGatewayConnection,
  OnGatewayDisconnect,
  ConnectedSocket,
  MessageBody,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { GameService } from './game.service';

@WebSocketGateway({
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  },
})
export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(private readonly gameService: GameService) {}

  handleConnection(client: Socket) {
    console.log('Client connected:', client.id);
  }

  handleDisconnect(client: Socket) {
    console.log('Client disconnected:', client.id);
  }

  @SubscribeMessage('joinRoom')
  handleJoinRoom(
    @ConnectedSocket() client: Socket,
    @MessageBody() roomId: string,
  ) {
    client.join(roomId);
    const room = this.gameService.joinRoom(roomId, client.id);

    // 发送房间状态给新加入的玩家
    const roomState = this.gameService.getRoomState(roomId);
    client.emit('roomState', roomState);

    // 通知其他玩家有新玩家加入
    client.to(roomId).emit('playerJoined', client.id);
  }

  @SubscribeMessage('updatePuzzle')
  handleUpdatePuzzle(
    @ConnectedSocket() client: Socket,
    @MessageBody()
    data: {
      roomId: string;
      puzzleState: any;
      image: string;
      difficulty: number;
    },
  ) {
    const { roomId, puzzleState, image, difficulty } = data;
    this.gameService.updatePuzzleState(roomId, puzzleState, image, difficulty);
    client.to(roomId).emit('puzzleUpdated', { puzzleState, image, difficulty });
  }

  @SubscribeMessage('movePiece')
  handleMovePiece(
    @ConnectedSocket() client: Socket,
    @MessageBody()
    data: { roomId: string; pieceId: number; targetIndex: number },
  ) {
    const { roomId, pieceId, targetIndex } = data;
    client.to(roomId).emit('pieceMoved', { pieceId, targetIndex });
  }
}
